package net.pimpas.security.jaas.serviceprovider.auth;

import java.security.Principal;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import net.pimpas.security.jaas.serviceprovider.auth.login.principal.JAASPrincipal;
import net.pimpas.security.serviceprovider.auth.Subject;

public class JAASSubject implements Subject<JAASPrincipal> {

	private static final long serialVersionUID = -8419900257099637209L;
	
	private javax.security.auth.Subject subject;
	
	public JAASSubject() {
		this.setSubject(new javax.security.auth.Subject());
	}
	
	public JAASSubject(javax.security.auth.Subject s) {
		this.setSubject(s);
	}
	
	public javax.security.auth.Subject getSubject() {
		return subject;
	}
	
	public void setSubject(javax.security.auth.Subject subject) {
		this.subject = subject;
	}

	public <T extends Principal> Set<T> getPrincipals(Class<T> c) {
		return subject.getPrincipals(c);
	}

	public Set<Object> getPrivateCredentials() {
		return subject.getPrivateCredentials();
	}

	public Set<Object> getPublicCredentials() {
		return subject.getPublicCredentials();
	}

	public boolean isReadOnly() {
		return subject.isReadOnly();
	}

	public void setReadOnly() {
		subject.setReadOnly();
	}

	public void addPrincipal(JAASPrincipal principal) {
		this.getSubject().getPrincipals().add(principal);
	}

	public boolean containsPrincipal(JAASPrincipal principal) {
		return this.getSubject().getPrincipals().contains(principal);
	}

	public Set<JAASPrincipal> getPrincipals() {
		Set<JAASPrincipal> s = new HashSet<JAASPrincipal>();
		for (Iterator iter = this.getSubject().getPrincipals().iterator(); iter.hasNext();)
			s.add((JAASPrincipal) iter.next());
		
		return s;
	}

	public Set<?> getPrivateCredentials(Class<?> c) {
		return this.getSubject().getPrivateCredentials(c);
	}

	public Set<?> getPublicCredentials(Class<?> c) {
		return this.getSubject().getPublicCredentials(c);
	}

	public JAASPrincipal removePrincipal(JAASPrincipal principal) {
		return (this.getSubject().getPrincipals().remove(principal)) ? principal : null;
	}

	public JAASPrincipal getPrincipal(String name) {
		JAASPrincipal element = null;
		for (Iterator iter = this.getSubject().getPrincipals().iterator(); iter.hasNext();) {
			element = (JAASPrincipal) iter.next();
			if(element.getName().equals(name)) return element;
		}
		return null;
	}
}